package com.lizk.net.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class Client {
	public static void main(String... args) throws Exception {  
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();  
        client.connect(new InetSocketAddress("localhost", 10001)).get();  
        //client.write(ByteBuffer.wrap("test".getBytes())).get();
        
        ByteBuffer b = ByteBuffer.wrap("test".getBytes());
        client.write(b, b, new CompletionHandler<Integer, ByteBuffer>(){
			@Override
			public void completed(Integer result, ByteBuffer attachment) {
				if(attachment.hasRemaining()){
					client.write(attachment,attachment,this);
				}else{
					ByteBuffer b = ByteBuffer.allocate(1024);
					client.read(b, b, new CompletionHandler<Integer, ByteBuffer>(){

						@Override
						public void completed(Integer result, ByteBuffer attachment) {
							attachment.flip();
							byte[] b = new byte[attachment.remaining()];
							attachment.get(b);
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							System.out.println(new String (b));
						}

						@Override
						public void failed(Throwable exc, ByteBuffer attachment) {
							
						}
						
					});
				}
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				
			}
        	
        });
     
        
        Thread.sleep(2000);
        client.close();
    }  
}
